package com.micro.platform.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.micro.platform.starter.utils.AssertUtil;
import com.micro.platform.user.entity.UserRole;
import com.micro.platform.user.mapper.UserRoleMapper;
import com.micro.platform.user.service.UserRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 用户-用户角色关联表 服务实现类
 * </p>
 *
 * @author zhouyk
 * @since 2021-12-06
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {

    @Override
    public List<UserRole> getUserRolesByUserId(Long userId) {
        QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
        userRoleQueryWrapper.lambda()
                .eq(UserRole::getUserId, userId)
                .eq(UserRole::getDeleted, Boolean.FALSE);
        return this.list(userRoleQueryWrapper);
    }
    @Override
    public UserRole getUserRoleByRoleId(Long roleId) {
        QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
        userRoleQueryWrapper
                .lambda()
                .eq(UserRole::getRoleId, roleId)
                .eq(UserRole::getDeleted, Boolean.FALSE);
        return this.getOne(userRoleQueryWrapper, Boolean.FALSE);
    }

    @Override
    public List<UserRole> getUserRolesByUserIds(List<Long> userIds) {
        if(CollectionUtils.isEmpty(userIds)){
            return Collections.EMPTY_LIST;
        }
        QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
        userRoleQueryWrapper
                .lambda()
                .in(UserRole::getUserId, userIds)
                .eq(UserRole::getDeleted, Boolean.FALSE);
        return this.list(userRoleQueryWrapper);
    }

    @Override
    public Boolean deletedUserRoleByUserId(Long userId) {
        UpdateWrapper<UserRole> userRoleUpdateWrapper = new UpdateWrapper<>();
        userRoleUpdateWrapper
                .lambda()
                .eq(UserRole::getUserId, userId)
                .set(UserRole::getDeleted, Boolean.TRUE);
        return this.update(userRoleUpdateWrapper);
    }

    @Override
    @Transactional
    public Boolean UpdateBatch(List<UserRole> lstUserRole, Long userId) {
        if(CollectionUtils.isEmpty(lstUserRole) || null == userId){
            return Boolean.TRUE;
        }
        Boolean aBoolean = deletedUserRoleByUserId(userId);
        if(aBoolean){
            aBoolean = aBoolean && this.saveBatch(lstUserRole);
        }
        AssertUtil.isTrue(aBoolean, "更新用户角色关系失败");
        return aBoolean;
    }
}
